package com.useeinfo.oa.modules.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Area;
import com.useeinfo.oa.modules.base.entity.DictInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/7 15:46
 * @Description:
 */
@Repository("areaDao")
public class AreaDao implements CrudDao<Area> {

    private final static Logger logger = LoggerFactory.getLogger(AreaDao.class);

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        String searchCode = queryHash.get("searchCode");
        if (!StringUtils.isEmpty(searchCode)) {
            conditionHash.put("(s.areaName like ?{paramIndex}) ", "%" + searchCode + "%");
        }
        String areaName = queryHash.get("areaName");
        if (!StringUtils.isEmpty(areaName)) {
            conditionHash.put("(s.areaName = ?{paramIndex}) ", areaName);
        }
        String areaCode = queryHash.get("areaCode");
        if (!StringUtils.isEmpty(areaCode)) {
            conditionHash.put("(s.areaCode = ?{paramIndex}) ", areaCode);
        }
        String bigParent = queryHash.get("bigParent");//查根节点
        if (!StringUtils.isEmpty(bigParent)) {
            conditionHash.put("(s.parentId is null or s.parentId = ?{paramIndex}) ", 0L);
        }
        String parentId = queryHash.get("parentId");
        if (!StringUtils.isEmpty(parentId)) {
            conditionHash.put("(s.parentId = ?{paramIndex}) ", StringConverters.ToLong(parentId));
        }
        String parentIds = queryHash.get("parentIds");
        if (!StringUtils.isEmpty(parentIds)) {
            conditionHash.put("(s.parentId in ("+parentIds+") and 1= ?{paramIndex}) ", 1);
        }
        String rootId = queryHash.get("rootId");
        if (!StringUtils.isEmpty(rootId)) {
            conditionHash.put("(s.rootId = ?{paramIndex}) ", StringConverters.ToLong(rootId));
        }
        String ancestryId = queryHash.get("ancestryId");
        if (!StringUtils.isEmpty(ancestryId)) {
            conditionHash.put("(s.parentIds like ?{paramIndex} or fc.parentIds like '%," + ancestryId + ",%' or fc.parentIds = '" + ancestryId + "' or fc.parentIds like '%," + ancestryId + "') ", ancestryId + ",%");
        }
        String enterpriseId = queryHash.get("enterpriseId");
        if (!StringUtils.isEmpty(enterpriseId)) {
            conditionHash.put("(s.enterprise.id = ?{paramIndex}) ", StringConverters.ToLong(enterpriseId));
        }
        String magicLike = queryHash.get("magicLike");
        if (StringUtils.isNotBlank(magicLike)) {
            conditionHash.put("areaName like ?{paramIndex} ", "%" + magicLike + "%");
        }
        String magicId = queryHash.get("magicId");
        if (StringUtils.isNotBlank(magicId)) {
            conditionHash.put("id != ?{paramIndex} ", StringConverters.ToLong(magicId));
        }
        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {
        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from Area s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<Area> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from Area s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<Area> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, Area.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public Area findModel(Long id) {
        return entityManager.find(Area.class, id);
    }

    @Override
    public Integer add(Area model) {
        model.setCreateDate(new Date());
        entityManager.persist(model);
        logger.info("AreaDaoImpl添加areaInfo成功！");
        return 1;
    }

    @Override
    public Integer update(Area model) {
        model.setUpdateDate(new Date());
        entityManager.merge(model);
        return 1;
    }

    @Override
    public Integer delete(Long id) {
        Area area = entityManager.find(Area.class, id);
        entityManager.remove(area);
        return 1;
    }

    @Override
    public Integer deleteLogic(Area model) {
        model.setDeleteStatus(true);
        return 1;
    }

    public List<Area> hqlExcute(String hql) {
        return entityManager.createQuery(hql, Area.class).getResultList();
    }

    /**
     * 获取区域
     */
    public List<Object> getAreaListByEnterprise(Map<String, Object> dataMap) {
        Long enterpriseId = StringConverters.ToLong(dataMap.get("enterpriseId") + "");
        String sql = "SELECT a.id,a.area_name FROM area a\n" +
                "LEFT JOIN enterprise b\n" +
                "ON a.enterprise_id=b.id\n" +
                "where a.delete_status=FALSE\n";
        if (enterpriseId != null && enterpriseId > 0) {
            sql += "and b.parent_ids LIKE '%," + enterpriseId + ",%'";
        }
        sql=sql+"order by a.id";
        return entityManager.createNativeQuery(sql).getResultList();
    }
}
